package cn.zhao.service;

import cn.zhao.dao.UserMapper;
import cn.zhao.entity.JwtUserDto;
import cn.zhao.entity.User;
import cn.zhao.service.impl.LoginService;
import cn.zhao.utils.JwtUtil;
import cn.zhao.utils.RedisCache;
import cn.zhao.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {
        String token = null;
        //1.authenticationManager进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            //2.认证通过，使用jwt生成token，并存入ResponseResult返回
            JwtUserDto jwtUserDto = (JwtUserDto)authenticate.getPrincipal();

            //3.存入redis
            int id = jwtUserDto.getUser().getId();
            token = JwtUtil.createJWT(String.valueOf(id));

            //4.将用户信息放入redis中
            redisCache.setCacheObject("login:" + id,jwtUserDto);
        }catch (Exception e){
            throw new RuntimeException("验证失败！");
        }

        return new ResponseResult(200,"成功",token);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        User user = (User)authentication.getPrincipal();
        redisCache.deleteObject("login:"+user.getId());
        return new ResponseResult(200,"成功");
    }
}
